package cn.njyd.corejava.thread.myday02;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class BankAccount{
    private String id;
    private int balance = 500;
    private Lock lock = new ReentrantLock();

    public void deposit(int money){
        lock.lock();
        try{
            this.balance+=money;
            System.out.println(Thread.currentThread().getName()+this.balance);
        } finally {
            lock.unlock();
        }
    }


    public void withDraw(int money) {
        lock.lock();
        try {
            if (this.balance-money<0) {
                System.out.println(Thread.currentThread().getName()+"余额不足");
                return;
            }
            this.balance-=money;
            System.out.println(Thread.currentThread().getName()+"账户"+id+"取款成功，余额为"+this.balance);
        } finally {
            lock.unlock();
        }
    }

}


public class LockDemo02 {
    public static void main(String[] args) {
        BankAccount bankAccount = new BankAccount();
        for (int i=1;i<=50;i++) {
            final int k = i;
            new Thread(()->{
               if (k%2 == 0) {
                   bankAccount.deposit(50);
               } else {
                   bankAccount.withDraw(100);
               }
            },"ATM"+i).start();
        }
    }
}
